from django.shortcuts import render

# Create your views here.
from rest_framework.viewsets import ReadOnlyModelViewSet


# 视图集合需要listmodelmixin和retrimodelmixin.
# GET/areas/:{'get': 'list'},只返回顶级数据.
# GET/areas/pk/:{'get': 'retrive'},获取单一对象都返回
from rest_framework_extensions.cache.mixins import CacheResponseMixin

from areas.models import Area
from areas.serializers import AreaSerializer, SubAreaSerializer


class AreasViewSet(CacheResponseMixin, ReadOnlyModelViewSet):
    """实现上面两个方法"""
    # 需要根据action返回不同的查询集和序列化器
    # 关闭分页
    pagination_class = None
    def get_serializer_class(self):
        if self.action == 'list':
            return AreaSerializer
        else:
            return SubAreaSerializer

    def get_queryset(self):
        if self.action == 'list':
            return Area.objects.filter(parent=None)
        else:
            return Area.objects.all()

# 数据操作频繁,数据放到redis里面,第一次找缓存找不到,到数据库中复制一份到缓存中,下次再找.
# CacheResponseMixin使用类只能全局指明配置信息


